<?php
namespace app\newapi\controller;

use app\common\model\WxUser as WxUserModel;
use app\common\model\AuthorWxUser as AuthorWxUserModel;
use app\common\model\Users as UsersModel;
use app\common\util\WechatThirdUtil;
use htq\HTQClient; //队列类
use think\Controller;
use think\Session;
use think\Db;

class Sync extends Controller
{   
    protected $wechat_obj;
    protected $author_wx_user;
    protected $author_wx_user_model;
    protected $wx_user;
    protected $users_model;
    protected $HTQClient;

    protected function _initialize()
    {
        parent::_initialize();
        $this->wx_user = new WxUserModel();
        $this->author_wx_user_model = new AuthorWxUserModel;
        $this->config = $this->wx_user->find();//第三方平台
        $this->HTQClient = new HTQClient('J6E04AifABuDRfsMm2Qt4WMJHq201vmz','Hc9KVU6cGDWxoQ7PjSxwYQOLrCcg6wFj');
    }

    public function syncPubInfo(){
        //获取授权公众号基本信息
        $base_info = $this->wechat_obj->getAuthorizerInfo();
        $wechat_base_info = $base_info['authorizer_info'];
        $data = [
            'wxname'                   => $wechat_base_info['nick_name'],   //微信公众号名字
            'headerpic'                => isset($wechat_base_info['head_img']) ? $wechat_base_info['head_img'] : '', //微信公众号头像
            'type'                     => $wechat_base_info['service_type_info']['id'], //微信公众号类型
            'verify_type'              => $wechat_base_info['verify_type_info'], //授权方认证类型
            'weixin'                   => isset($wechat_base_info['alias']) ? $wechat_base_info['alias'] : '', //微信号
            'qr'                       => $wechat_base_info['qrcode_url'], //二维码图片的URL
            'idc'                      => $wechat_base_info['idc'],
            'principal_name'           => $wechat_base_info['principal_name'], //公众号的主体名称
            'signature'                => $wechat_base_info['signature'], //公众号的主体名称
            'business_info'            => serialize($wechat_base_info['business_info']), //功能
            'funcscope_category'       => serialize($base_info['authorization_info']['func_info']), //授权给开发者的权限集列表
        ];

        $result = $this->author_wx_user_model->save($data,['appid'=>$base_info['authorization_info']['authorizer_appid'],'authorized'=>1]);
        if($result){
            return json(['msg'=>'同步完成']);
        } else {
            return json(['msg'=>'同步失败']);
        }
    }

    /**
     * 同步粉丝信息
     */
    public function syncFansInfo($id){
        if($this->request->isPost()){
            $data = $this->request->post();
            $template_msg = $data['data'];

            $this->author_wx_user = $this->author_wx_user_model->where('id',$id)->find();
            $this->wechat_obj = new WechatThirdUtil($this->config , $this->author_wx_user);
    
            $arr = $this->wechat_obj->getFanIdList();
            if($arr['total'] != 0){
                    $j = $arr['total'] / $arr['count'];
                    for($i = 0; $i < $j; $i++){
                        $chunk_arr = array_chunk($arr['data']['openid'],100);
                        foreach($chunk_arr as $v){
                            $openid_list = [];
                            foreach($v as $v2){
                                $openid_list[] = ['openid' => $v2];
                            }
                            $data = $this->wechat_obj->getBatchget($openid_list);
                            foreach($data['user_info_list'] as $user){
                                // dump($user['openid']);exit();
                                $this->users_model = new UsersModel;
                                $openid = $this->users_model->where('openid',$user['openid'])->value('openid');
                                if($openid){
                                    $this->users_model->allowField(true)->save($user,['openid' => $openid]);
                                }else{
                                    $this->users_model = new UsersModel;
                                    $user['auid'] = $id;
                                    $this->users_model->allowField(true)->save($user);
                                }
                            }
                        }
                        if($j > $i){
                            $arr = $this->wechat_obj->getFanIdList($arr['next_openid']);
                        }
                    }
                    //队列全部执行完并提醒管理员 return只是暂时的 删除队列
                    $return = $this->HTQClient->deleteQueue($template_msg['queue_name']);
                    if($return['error_code'] == 1004){
                        //删除失败
                        return false;
                    }
                    return json(['status' => 1 ,'msg' => 'ok']);
            }
        }
    }
}